package com.ruiyin.httpinte;

import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.NotAction;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.jfinal.MsgController;
import com.jfinal.weixin.sdk.jfinal.MsgInterceptor;
import com.jfinal.weixin.sdk.kit.MsgEncryptKit;
import com.jfinal.weixin.sdk.msg.InMsgParser;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMassEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InPoiCheckNotifyEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InShakearoundUserShakeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifyFailEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifySuccessEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.ruiyin.bean.Microchannelinformation;
import com.ruiyin.bean.Microchannelstate;
import com.ruiyin.controller.BaseController;
import com.ruiyin.httpinte.TradeCode;
import com.ruiyin.service.MicrochannelstateService;
import com.ruiyin.util.JsonUtil;
import com.ruiyin.util.TemplateApi;


public class HttpInterFaceController  extends BaseController{
	
	SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
	private static Logger log = Logger.getLogger(HttpInterFaceController.class);
	
	public void index(){
		
	}
	
	public void mainMethod(){
		String jsonparam=getPara("jsonparam");;
		String param="";
		String result="";
		 Map<String, Object> map=null;
	try {
		//截取报文头8位获取报体的字符串长度
		param = jsonparam.substring(0,8);
		 //转换成数字
		Integer len = Integer.parseInt(param);
		 //根据数字截取报文后面的json串
		String body = jsonparam.substring(8,len+8);
		 //json2map
		map = JsonUtil.jsonToMap(body);
		 
		 //解析报头获取交易代码
		String headString =  map.get("head").toString();
		Head head = new Head();
		head=JsonUtil.jsonToBean(headString, head.getClass());
		String tradecode = head.getTradecode();
		//查询是否有用户关注/取消关注
//		if(tradecode.equals(TradeCode.UpdateMicrochannel)){
//			result=this.updateMicrochannel(map);
//		}
//		
//		//查询是否有用户关注/取消关注
//		if(tradecode.equals(TradeCode.DeleteMicrochannel)){
//			result=this.deleteMicrochannel(map);
//		}
//		
//		//查询所有关注用户的信息
//		if(tradecode.equals(TradeCode.AllAttentionUsers)){
//			result=this.allAttentionUsers(map);
//		}

		
	} catch (Exception e) {
		e.printStackTrace();
		result=error(map,"解析json参数错误");
	}   
	   try {
		  // PrintWriter out = response.getWriter();  
		  // out.print(result);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		renderJson(result);
	}

	/**
	 * 错误信息
	 * @param map
	 * @param errorMsg
	 * @return
	 */
	private String error(Map<String, Object> map,String errorMsg){
		JSONObject resultMap = new JSONObject();
		Map<String,Object> bodyMap = new HashMap<String, Object>();
		String headString =  map.get("head").toString();
		Head head = new Head();
		head=JsonUtil.jsonToBean(headString, head.getClass());
		resultMap.element("head", head);
		bodyMap.put("result", "1");
		bodyMap.put("msg", errorMsg);
		resultMap.element("body", bodyMap);
		return resultMap.toString();
	}
	
	/**
	 * 查询是否有用户关注/取消关注
	 * @author 
	 * @since 1.1  2016-07-18
	 */
	public void updateMicrochannel() {
		JSONObject Map = new JSONObject();
		log.info("查询新用户openid");
		
		JSONObject jo  = new JSONObject();
		
		try {
			MicrochannelstateService microchannelstateService = new MicrochannelstateService();
			
			List<Microchannelstate> list = microchannelstateService.paginate();
				Map.put("result", "0");
				//Map.put("msg", "信息获取成功！");
				Map.put("data", list);
		} catch (Exception e) {
			Map.put("result", "1");
			//Map.put("msg", "信息获取失败！");
			e.printStackTrace();
		}
		log.info("查询新用户信息:"+Map);
		renderJson(Map);
	}
	
	/**
	 * 头像信息上传后删除Microchannelstate表中的信息
	 * @author 
	 * @since 1.1  2016-07-18
	 */
	public void deleteMicrochannel() {
		JSONObject Map = new JSONObject();
		String openids = getPara("openid").toString();
		log.info("删除Microchannelstate表中的信息");
		log.info("参数openid："+openids);
		
		JSONObject jo  = new JSONObject();
		
		try {
			MicrochannelstateService microchannelstateService = new MicrochannelstateService();
			microchannelstateService.delete(openids);
//			if(openids!=null){
////				if(openids.length()>1){
////					openids = openids.substring(1, openids.length()-1);
////					String[] openid = openids.split(",");
////					for (int i=0;i<openid.length;i++){
////						MicrochannelstateService microchannelstateService = new MicrochannelstateService();
////						microchannelstateService.delete(openid[i].replace("\"", ""));
////					}
////				}
////			}
				Map.put("result", "0");
		} catch (Exception e) {
			Map.put("result", "1");
			e.printStackTrace();
		}
		
		log.info("信息删除结果:"+Map);
		renderJson(Map);
	}
	
	/**
	 * 查询所有关注用户的信息
	 * @author 
	 * @since 1.1  2016-07-18
	 */
	public void allAttentionUsers() {
		JSONObject Map = new JSONObject();
		log.info("查询所有关注用户的信息");
		
		try {
			MicrochannelstateService microchannelstateService = new MicrochannelstateService();
			List<Microchannelinformation> list = microchannelstateService.allAttentionUsers();
			microchannelstateService.deleteAll();
			Map.put("data", list);
			Map.put("result", "0");
			Map.put("msg", "信息查询成功！");
		} catch (Exception e) {
			Map.put("result", "1");
			Map.put("msg", "信息查询失败！");
			e.printStackTrace();
		}
		log.info("信息查询结果:"+Map);
		renderJson(Map);
	}
	

	
	/**
	 * 模板消息
	 * @author 
	 * @throws UnsupportedEncodingException 
	 * @since 1.1  2016-07-18
	 */
	public void Messagetemplates() throws UnsupportedEncodingException {
		// 开发模式输出微信服务发送过来的  xml 消息

		// 解析消息并根据消息类型分发到相应的处理方法
		String str = " {\n" +
		"           \"touser\":\"o7gYjwNEQfCR4td9KCK7mDGoE61I\",\n" +
		"           \"template_id\":\"JaNUY3PYDAd2yyL9-wzky0JVD7yvuhVCqdW-gEwRypM\",\n" +
		"           \"url\":\"http://www.baidu.com\",\n" +
		"           \"topcolor\":\"#FF0000\",\n" +
		"           \"data\":{\n" +
		"                   \"first\": {\n" +
		"                       \"value\":\"您好，您已排队\",\n" +   
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword1\":{\n" +
		"                       \"value\":\"A011\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword2\":{\n" +
		"                       \"value\":\"2016-8-29\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword3\":{\n" +
		"                       \"value\":\"545566666**234\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword4\":{\n" +
		"                       \"value\":\"南昌市中山路159号总行营业部\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword5\":{\n" +
		"                       \"value\":\"0791-86790777\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"remark\":{\n" +
		"                       \"value\":\"备注：请您提前至营业网点刷卡取号，以免失效！\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   }\n" +
		"           }\n" +
		"       }";
		String appIDs = PropKit.get("appId");
		String appSecrets = PropKit.get("appSecret");
		String requestUrl= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appIDs+"&secret="+appSecrets;
		String sendApiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
		String jsonResult = HttpUtils.get(requestUrl);
		JSONObject jsonObject  = JSONObject.fromObject(jsonResult);
		//JSONObject jsonObject = httpRequst(requestUrl, "GET", null);
		//JSONObject jsonObjects = httpRequst(sendApiUrl + URLDecoder.decode(jsonObject.get("access_token").toString(),"UTF-8"), "GET", str);
		String  json = HttpUtils.post(sendApiUrl + URLDecoder.decode(jsonObject.get("access_token").toString(),"UTF-8"), str);
		JSONObject jsonObjects  = JSONObject.fromObject(json);
		renderJson(jsonObjects);
	}
	
	public JSONObject httpRequst(String requestUrl,String requetMethod,String outputStr){
		JSONObject jsonobject=null;
		StringBuffer buffer=new StringBuffer();
		try
		{
			//创建SSLContext对象，并使用我们指定的新人管理器初始化
			TrustManager[] tm={new MyX509TrustManager()};
			SSLContext sslcontext=SSLContext.getInstance("SSL","SunJSSE");
			sslcontext.init(null, tm, new java.security.SecureRandom());
			//从上述SSLContext对象中得到SSLSocktFactory对象
			SSLSocketFactory ssf=sslcontext.getSocketFactory();
			
			URL url=new URL(requestUrl);
			HttpsURLConnection httpUrlConn=(HttpsURLConnection)url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			//设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requetMethod);
			
			if("GET".equalsIgnoreCase(requetMethod))
				httpUrlConn.connect();
			
			//当有数据需要提交时
			if(null!=outputStr)
			{
			OutputStream outputStream=httpUrlConn.getOutputStream();
			//注意编码格式，防止中文乱码
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
			}
			
			//将返回的输入流转换成字符串
			InputStream inputStream=httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
			BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
			
			
			String str=null;
			while((str = bufferedReader.readLine()) !=null)
			{ 
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			//释放资源
			inputStream.close();
			inputStream=null;
			httpUrlConn.disconnect();
			jsonobject=JSONObject.fromObject(buffer.toString());
		}
		catch (ConnectException ce) {
			// TODO: handle exception
			ce.printStackTrace();
		}
		catch (Exception e) { 
			e.printStackTrace();
		}
		return jsonobject;
	}


		
    
}

class MyX509TrustManager implements X509TrustManager
{

	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}


}
